package com.ytkj.digitalConstruction.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 日期操作工具类
 *
 * @author liuht
 * @phone 13823600456
 * @email laupete@qq.com
 * @date 2018年1月30日
 */
public class DateUtil {
	private final static Logger log = LoggerFactory.getLogger(DateUtil.class);

	private static String DEFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
	private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DEFAULT_DATE_FORMAT);

	/** 私有化构造方法 */
	private DateUtil() {
	}

	private DateUtil(SimpleDateFormat simpleDateFormat) {
		DateUtil.simpleDateFormat = simpleDateFormat;
	}

	/**
	 * 将日期转换成字符型
	 * 
	 * @param date
	 * @return
	 */
	public static String dateToString(Date date) {
		return simpleDateFormat.format(date);
	}

	/**
	 * 
	 * @param strDate
	 * @return
	 * @throws ParseException
	 */
	public static Date stringToDate(String strDate) {
		try {
			return simpleDateFormat.parse(strDate);
		} catch (ParseException e) {
			log.error("string convert to Date error.", e);
		}
		return null;
	}

	/**
	 * 判断格式化日期大小
	 * 
	 * @param start
	 * @param end
	 * @return false if Date string convert error
	 */
	public static boolean before(String start, String end) {
		Date sDate = stringToDate(end);
		if (sDate == null) {
			return false;
		}
		return stringToDate(start).before(stringToDate(end));
	}

	/**
	 * 格式化日期按秒增加
	 * 
	 * @param str
	 * @return "" if Date string convert error
	 */
	public static String increaseBySec(String str) {
		Date date = stringToDate(str);
		if (date == null) {
			return "";
		}
		return dateToString(increaseBySec(date));
	}

	/**
	 * 日期按秒增加
	 * 
	 * @param date
	 * @return
	 */
	public static Date increaseBySec(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.SECOND, 1);
		return increaseBySecs(date, 1);
	}

	/**
	 * 日期按秒增加
	 * 
	 * @param date
	 * @param seconds
	 * @return
	 */
	public static Date increaseBySecs(Date date, int seconds) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.SECOND, seconds);
		return calendar.getTime();
	}

	/**
	 * 当前日期按秒增加
	 * 
	 * @return
	 */
	public static Date increaseBySec() {
		return increaseBySec(new Date());
	}

	/**
	 * 目的是实现一个一次调用的方法 TODO 后面继续改造
	 * 
	 * @param patten
	 * @return
	 */
	@Deprecated
	public static DateUtil format(String patten) {
		DateUtil.simpleDateFormat = new SimpleDateFormat(patten);
		return new DateUtil(simpleDateFormat);
	}

}